package com.xxx.controller;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.xxx.constant.SystemConstants;

import java.util.Collection;

/**
 * session管理Controller
 */
@RequiresPermissions("session:*")
@Controller
public class SessionController {
	
	@Autowired
	private SessionDAO sessionDAO;
//	private MySessionDaoImpl sessionDAO; // 使用自定义sessionDAO（有个问题未解决：强制退出）

	/**
	 * 全部session列表
	 * @param model
	 * @return
	 */
	@RequestMapping("/sessions")
	public String list(Model model) {
		// 以下方法有个缺点是：当session数量较多时，无法进行分页获取
		Collection<Session> sessions = sessionDAO.getActiveSessions();
		model.addAttribute("sessionCount", sessions.size());
		model.addAttribute("sessions", sessions);
		return "sessions/list";
	}
	
//	/**
//	 * 分页查询session列表
//	 * @param model
//	 * @return
//	 */
//	@RequestMapping("/sessionsPage")
//	public String page(Model model) {
//		// 从数据库中分页查询session列表
//		int sessionCount = sessionDAO.getActiveSessionsCount();
//		List<Session> page = sessionDAO.getActiveSessionsByPage(1, 10);
//		model.addAttribute("sessionCount", sessionCount);
//		model.addAttribute("sessions", page);
//		return "sessions/list";
//	}

	/**
	 * 强制退出
	 * @param sessionId
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping("/{sessionId}/forceLogout")
	public String forceLogout(@PathVariable("sessionId") String sessionId, RedirectAttributes redirectAttributes) {
		try {
//			Session session = sessionDAO.doReadSession(sessionId);
			Session session = sessionDAO.readSession(sessionId);
			if (session != null) {
				session.setAttribute(SystemConstants.SESSION_FORCE_LOGOUT_KEY, Boolean.TRUE);
			}
			System.out.println(session.getId());
		} catch (Exception e) {
			System.err.println(e);
		}
		
		redirectAttributes.addFlashAttribute("msg", "强制退出成功！");
		return "redirect:/sessions";
	}

}
